<template>
  <div style="padding: 15px;">
    <el-form ref="form" :rules="rules" :model="form" label-width="80px">
      <el-row>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item  label="订单号">
              <el-input v-model="form.code" style="width:75%"  :disabled="true"/>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item label="所属仓库" >
              <el-select v-model="form.warehouseCode" placeholder="请输入所属仓库  " style="width:75%" :disabled="true">
                <el-option
                  v-for="item in warehouseData"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item  label="入驻商" label-width="100px">
              <el-input v-model="form.shipmentName" style="width:75%"  :disabled="true"/>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item  label="单据类型">
              <el-input v-model="typeText" style="width:75%"  :disabled="true"/>
            </el-form-item>
          </div>
        </el-col>

        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item  label="客户">
              <el-input v-model="form.customerName" style="width:75%"  :disabled="true"/>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="19">
          <div class="grid-content bg-purple">
            <el-form-item  label="备注">
              <el-input v-model="form.remarks" style="width:75%"  :disabled="true"/>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
    </el-form>
    <vxe-table
      border
      resizable
      show-overflow
      ref="xTable"
      :align="allAlign"
      :data="tableData"
      show-footer
      :edit-rules="validRules"
      :footer-method="footerMethod"
      :span-method="objectSpanMethod"
      :edit-config="{trigger: 'click', mode: 'cell'}"
      @edit-actived="editActiveEvent"
      auto-resize
    >
      <vxe-table-column type="seq" width="60"></vxe-table-column>
      <!-- <vxe-table-column field="receiveCode" title="" width="0" ></vxe-table-column> -->
      <vxe-table-column field="goodsName" title="商品名称" width="270"></vxe-table-column>
      <vxe-table-column field="goodCode" title="商品编码"  width="120"></vxe-table-column>
      <vxe-table-column field="goodsBarCode" title="商品条码"  width="120"></vxe-table-column>
      <vxe-table-column field="goodsUnitName" title="单位" width="100"></vxe-table-column>
      <vxe-table-column field="locationName" title="分配库位" width="120" ></vxe-table-column>
      <vxe-table-column field="distributionQuantity" title="分配数量"  width="100"></vxe-table-column>
      <vxe-table-column field="stockoutQuantity" title="缺货数量"  width="120" />
      <vxe-table-column field="statusText" title="拣货状态"  width="120"></vxe-table-column>
      <vxe-table-column field="pickingQuantity" title="拣货数量"  width="120" :edit-render="{name: 'input', attrs: {disabled: pickingQuantityEditActive}}"/>
      <vxe-table-column field="goodsStatusName" title="库存状态" width="120"></vxe-table-column>
      <vxe-table-column field="containerBarCode" title="容器号" width="120"></vxe-table-column>
      <vxe-table-column field="gmtManufacture" title="生产日期" width="120"></vxe-table-column>
      <vxe-table-column field="gmtExpire" title="过期日期" width="120"></vxe-table-column>
      <vxe-table-column field="supplier" title="供应商" width="120"></vxe-table-column>
      <vxe-table-column field="serialNumber" title="序列号" width="120"></vxe-table-column>
      <vxe-table-column field="extendOne" title="生产批号" width="120"></vxe-table-column>
      <vxe-table-column field="extendTwo" title="商品批次" width="120"></vxe-table-column>
      <vxe-table-column field="extendThree" title="扩展3" width="120"></vxe-table-column>
      <vxe-table-column field="extendFour" title="扩展4" width="120"></vxe-table-column>
      <vxe-table-column field="extendFive" title="扩展5" width="120"></vxe-table-column>
      <vxe-table-column field="extendSix" title="扩展6" width="120"></vxe-table-column>
      <vxe-table-column field="receiveLot" title="收货批次" width="120"></vxe-table-column>
      <vxe-table-column field="taskCode" title="任务号" width="120"></vxe-table-column>
      <vxe-table-column field="operatorName" title="作业人" width="120"></vxe-table-column>
      <vxe-table-column field="remarks" title="备注"  width="270"></vxe-table-column>
    </vxe-table>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="funcSubmitCheck" :disabled="isDisable" plain>确 认</el-button>
    </div>

  </div>
</template>
<script>
import Vue from 'vue'
import 'xe-utils'
import VXETable from 'vxe-table'
import 'vxe-table/lib/index.css'
import XEUtils from 'xe-utils'
import VXEUtils from 'vxe-utils'
import request from '@/utils/request'
import VXETablePluginElement from 'vxe-table-plugin-element'
import 'vxe-table-plugin-element/dist/style.css'
import {getWarehouse} from '@/api/basicInfo'
import {deliveryCheckSubmit ,pickingCheck, pickingDetail} from '@/api/outStorage'
Vue.use(VXETable, VXEUtils, XEUtils, { mounts: ['cookie'] })
VXETable.use(VXETablePluginElement)

Vue.use(VXETable, VXEUtils, XEUtils, { mounts: ['cookie'] })
VXETable.use(VXETablePluginElement)
export default {
  name: 'Parent',
  components: {
  },
  data() {
    return {
      allAlign:'center',
      warehouseData:[],
      units:[],
      modelEditFlag: false,
      isShow0:false,
      isShow1:false,
      isDisable:false,                                                                          //确定键显示按钮
      form: {
        code: '',                                                                      //收货单号 ,
        customerCode: '',                                                                      //客户 ,
        customerName: '',
        gmtPlanArrival: '',                                                                      //计划到货日期 ,
        groupCode: '',                                                                      //所属机构Code ,
        putawayQuantity: '',                                                                      //上架数量 ,
        receivedQuantity: '',                                                                      //收货数量 ,
        remarks: '',                                                                      //备注 ,
        shipmentCode: '',                                                                      //入驻商 ,
        shipmentName:'',
        deliveryCode: '',                                                                      //来源单号 ,
        status: '',                                                                      //状态；0:新增；1：作废；2：待收货；3：部分收货；4：收货完成； ,
        supplierCode: '',                                                                      //供应商 ,
        totalQuantity: '',                                                                      //总数量 ,
        typeText: '',                                                                      //单据类型；0：收货单；1：退货单； ,
        warehouseCode: '',                                                                      //仓库
        pickingItemWithRegisterVOList: []
      },
      loading: false,
      spanArr: [],  // 合并单元格数组
      pos: 0,
      mergeColumnIndex: [1,2,3,4,5,6,7],  // 需要合并的列号
      tableData: [
      ],
      rules: {
        shipmentCode: [
          { required: true, message: '请输入客户姓名', trigger: 'change' }
        ],
        warehouseCode: [
          { required: true, message: '请选择仓库', trigger: 'change' }
        ],
        supplierCode: [
          { required: true, message: '请选择供应商', trigger: 'change' }
        ],

      },
      validRules: {
        goodsName: [
          { required: true, message: '商品名称必须填写' },
        ],
        goodsUnit: [
          { required: true, message: '单位必须填写' },
        ],
        pickingQuantity: [
          { required: true, message: '数量必须填写' },
          { pattern: /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d{0,6})$/, message: '数量必须大于0并且保留六位小数' }
        ],
      },
      listQuery: {
        page: 1,
        limit: 13,
        totalzong: 0
      },
      // 拣货数量是否可编辑标志位
      pickingQuantityEditActive: false,
    }
  },
  created() {
    this.getWarehouse()
  },
  computed:{
    typeText(){
      if(this.form.type == '0'){
        return '销售发货';
      } else if(this.form.type == '2'){
        return '领用发货';
      }else if(this.form.type == '5'){
        return '调拨发货';
      }
    },
    // 去重表格数据，用于统计
    distinctTableData(){
      let distinctData = []
      this.tableData.forEach(item=>{
        let flag = distinctData.some(e=>{
          if(item.pickingItemCode === e.pickingItemCode){
            return true;
          }
        })
        if(!flag){
          distinctData.push(item)
        }
      })

      return distinctData;
    }
  },
  methods: {
    // 获取页面信息
    getInfo() {
      this.loading = true
      let code = this.$route.query.code ? this.$route.query.code : ""
      pickingDetail(code).then(response => {
        this.form = response.data
        this.tableData = this.form.pickingItemWithRegisterVOList
        // 获取合并表格数组
        this.getSpanArr(this.tableData)
        this.loading = false
      })
    },
    //仓库查询
    getWarehouse(){
      getWarehouse().then(response => {
        this.warehouseData = response.data
      })
      this.getInfo()
    },
    // 提交
    async funcSubmitCheck() {
      this.form.pickingItemWithRegisterVOList = this.$refs.xTable.tableData
      const data = this.form
      let a = ''
      const errMap = await this.$refs.xTable.validate().catch(errMap => errMap)
      if (errMap) {
        this.$XModal.message({ status: 'error', message: '校验不通过！' })
      } else {
          this.form.pickingItemWithRegisterVOList.forEach( i => {
            if(i.pickingQuantity > i.distributionQuantity || i.pickingQuantity < 0){
              this.$message.error('拣货数量不可大于分配数量且不可为负')
              a =1
              return;
            }else{
              a = 0
            }
          })
          if(a == 0){
            this.isDisable = true
            pickingCheck(data).then(response => {
              this.$message({ message: response.msg, type: 'success' })
              this.$eventBus.$emit('refreshList')
              this.$store.dispatch('tagsView/delView', this.$route)
              this.$router.push({
                path: "/wms/picking"
              });
            }).finally(()=>{
              this.isDisable = false;
            })
          }
      }
    },
    // 获取合并单元格的范围
    getSpanArr(data) {
      for (let i = 0; i < data.length; i++) {
        if (i === 0) {
          this.spanArr.push(1);
          this.pos = 0
        } else {
          // 判断当前元素与上一个元素是否相同
          if (data[i].pickingItemCode === data[i - 1].pickingItemCode) {
            this.spanArr[this.pos] += 1;
            this.spanArr.push(0);
          } else {
            this.spanArr.push(1);
            this.pos = i;
          }
        }
      }
    },

    // 未拣货状态，拣货确认单显示未拣货数量；已拣货状态，则拣货确认单显示已拣货数量；
    /*formatPickingQuantity({cellValue, row}){
      if(row.status == 0){
        return row.notPickingQuantity;
      } else {
        return row.pickingQuantity;
      }
    },*/

    footerMethod ({ columns, data }) {
      return [
        columns.map((column, columnIndex) => {
          if (columnIndex === 1) {
            return '合计'
          }
          if (['distributionQuantity'].includes(column.property)) {
            return this.form.planQuantity
          }
          if (['pickingQuantity'].includes(column.property)) {
              return XEUtils.sum(data, column.property).toFixed(6)
          }
          if (['stockoutQuantity'].includes(column.property)) {
            return parseInt(XEUtils.sum(this.distinctTableData, column.property))
          }
          return '-'
        })
      ]
    },
    // 表格合并行
    objectSpanMethod({ row, rowIndex,column,  columnIndex }) {
      if (this.mergeColumnIndex.includes(columnIndex)) {
        const _row = this.spanArr[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col
        };
      }
    },
    // 已拣货的拣货数量禁止编辑
    editActiveEvent ({ rowIndex, row }) {
      this.pickingQuantityEditActive = row.status != '0'
    },
  }
}
</script>
<style lang="scss" scoped>
  .dialog-footer {
    margin: 150px auto;
    width: 90px;
    // float: right;
  }
  </style>

<style>
.vxe-table .vxe-body--column:not(.col--ellipsis), .vxe-table .vxe-footer--column:not(.col--ellipsis), .vxe-table .vxe-header--column:not(.col--ellipsis) {
 padding: 6px 0;
}
.vxe-toolbar{padding:0 0 10px 0}
</style>
